// 检查OpenAI API配置和连接状态
require('dotenv').config()

console.log('🔧 检查OpenAI配置...\n')

// 检查环境变量
console.log('环境变量状态:')
console.log('OPENAI_API_KEY:', process.env.OPENAI_API_KEY ? `***${process.env.OPENAI_API_KEY.slice(-4)}` : '❌未设置')
console.log('OPENAI_BASE_URL:', process.env.OPENAI_BASE_URL || '使用默认值')
console.log('OPENAI_MODEL:', process.env.OPENAI_MODEL || '使用默认值')
console.log('')

// 测试OpenAI API连接
async function testOpenAI() {
  try {
    console.log('🚀 测试OpenAI API连接...')
    
    const OpenAI = require('openai')
    
    const openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
      baseURL: process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1',
    })

    // 简单的API调用测试
    const completion = await openai.chat.completions.create({
      model: process.env.OPENAI_MODEL || 'gpt-3.5-turbo',
      messages: [
        {
          role: 'user',
          content: '请回复"测试成功"'
        }
      ],
      max_tokens: 10,
      temperature: 0,
    })

    const response = completion.choices[0]?.message?.content
    console.log('✅ OpenAI API连接成功!')
    console.log('📝 API响应:', response)
    
    return true
  } catch (error) {
    console.log('❌ OpenAI API连接失败!')
    console.log('错误信息:', error.message)
    
    if (error.message.includes('API key')) {
      console.log('\n💡 解决方案:')
      console.log('1. 检查.env文件中的OPENAI_API_KEY是否正确')
      console.log('2. 确认API密钥未过期')
      console.log('3. 查看OPENAI_SETUP.md了解配置方法')
    } else if (error.message.includes('network') || error.message.includes('timeout')) {
      console.log('\n💡 解决方案:')
      console.log('1. 检查网络连接')
      console.log('2. 如果在中国大陆，可能需要配置代理')
      console.log('3. 尝试使用其他网络环境')
    } else if (error.message.includes('quota') || error.message.includes('billing')) {
      console.log('\n💡 解决方案:')
      console.log('1. 检查OpenAI账户余额')
      console.log('2. 确认API使用配额')
      console.log('3. 考虑升级到付费计划')
    }
    
    return false
  }
}

// 测试智能解析API
async function testSmartParse() {
  console.log('\n📝 测试智能解析API...')
  
  try {
    const http = require('http')
    
    const testCases = [
      '今天下午1点15分开财务现金流讨论会',
      '明天上午9点和客户开会',
      '每天下班记得要打卡'
    ]
    
    for (const testCase of testCases) {
      console.log(`\n🧪 测试: "${testCase}"`)
      
      const postData = JSON.stringify({ text: testCase })
      
      const options = {
        hostname: 'localhost',
        port: 5000,
        path: '/api/ai/smart-parse',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(postData)
        }
      }
      
      const result = await new Promise((resolve, reject) => {
        const req = http.request(options, (res) => {
          let data = ''
          res.on('data', (chunk) => { data += chunk })
          res.on('end', () => {
            try {
              const parsed = JSON.parse(data)
              resolve({ status: res.statusCode, data: parsed })
            } catch (e) {
              resolve({ status: res.statusCode, data: data })
            }
          })
        })
        
        req.on('error', reject)
        req.write(postData)
        req.end()
      })
      
      console.log(`状态: ${result.status}`)
      if (result.data.success) {
        console.log('✅ 解析成功')
        console.log('标题:', result.data.result.title)
        console.log('日期:', result.data.result.dueDate || '无')
        console.log('分类:', result.data.result.category)
        console.log('标签:', result.data.result.tags.join(', ') || '无')
        if (result.data.warning) {
          console.log('⚠️ 警告:', result.data.warning)
        }
      } else {
        console.log('❌ 解析失败:', result.data.error)
      }
    }
  } catch (error) {
    console.log('❌ API测试失败:', error.message)
  }
}

async function main() {
  const openaiOk = await testOpenAI()
  
  console.log('\n' + '='.repeat(60))
  
  if (openaiOk) {
    await testSmartParse()
  } else {
    console.log('⚠️ OpenAI API连接失败，跳过智能解析测试')
    console.log('💡 请先解决OpenAI配置问题，然后重新测试')
  }
}

main().catch(console.error)
